package person.zjh.kaoyansharehub.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import person.zjh.kaoyansharehub.dto.PageCommentDTO;
import person.zjh.kaoyansharehub.dto.PageFavoriteDTO;
import person.zjh.kaoyansharehub.dto.PageMaterialDTO;
import person.zjh.kaoyansharehub.dto.SaveFavoriteDTO;
import person.zjh.kaoyansharehub.mapper.FavoriteMapper;
import person.zjh.kaoyansharehub.mapper.ImgCoverMapper;
import person.zjh.kaoyansharehub.mapper.MaterialMapper;
import person.zjh.kaoyansharehub.pojo.Favorite;
import person.zjh.kaoyansharehub.pojo.ImgCover;
import person.zjh.kaoyansharehub.pojo.Material;
import person.zjh.kaoyansharehub.result.PageResult;
import person.zjh.kaoyansharehub.result.Result;
import person.zjh.kaoyansharehub.service.FavoriteService;
import person.zjh.kaoyansharehub.vo.MaterialVO;

import java.util.List;

/**
 * @description: TODO
 * @author 郑佳豪
 * @date 2025/2/21 12:56
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
public class FavoriteServiceImpl  extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {
    private final FavoriteMapper favoriteMapper;
    private final ImgCoverMapper imgCoverMapper;

    @Override
    public Result saveFavorite(SaveFavoriteDTO requestParam) {
        Favorite favorite = Favorite.builder()
                .materialId(requestParam.getMaterialId())
                .userId(requestParam.getUserId())
                .build();
        favoriteMapper.insert(favorite);
        return Result.success();
    }

    @Override
    public PageResult getFavoriteByUserId(PageFavoriteDTO requestParam) {
        PageHelper.startPage(requestParam.getPageNum(),requestParam.getPageSize());
        List<Material> materialList = favoriteMapper.getUserFavoriteMaterial(requestParam);
        PageInfo<Material> pageInfo = new PageInfo(materialList);
        List<MaterialVO> materialVOS = BeanUtil.copyToList(materialList, MaterialVO.class);
        for (MaterialVO materialVO : materialVOS) {
            LambdaQueryWrapper<ImgCover> wrapper = new LambdaQueryWrapper<ImgCover>()
                    .eq(ImgCover::getMaterialId, materialVO.getMaterialId());
            ImgCover imgCover = imgCoverMapper.selectOne(wrapper);
            materialVO.setImgPath(imgCover.getImgPath());
        }

        return new PageResult(pageInfo.getTotal(),materialVOS);
    }

    @Override
    public Result getFavoriteCount(Long userId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getUserId, userId);
        Long count = favoriteMapper.selectCount(wrapper);
        return Result.success(count);

    }


}
